<?php
namespace App\Controller;

use App\Model\UserModel;
use lib\View;

class UserController
{
    public function register(){
        if(IS_POST){
            //校验数据
            $Post=input($_POST);
            //判断用户是否存在
            $user=new UserModel();
            if($user->get(['email'=>$Post['email']])){
                error('该邮箱已被注册');
            }
            //判断两次密码是否相同
            if($Post['logpass']!==$Post['confirmpwd']){
                error('两次密码不同!');
            }
            $data['username']=$_POST['username'];
            $data['email']=$_POST['email'];
            $data['password']=$_POST['logpass'];
            $data['last_login']=0;
            $data['join_at']=time();
            $data['pic']='img/no_pic.jpg';
            $data['introduce']='该用户比较懒,无介绍...';
            $res=$user->save($data);
            if($res){
                success('注册成功!','login');
            }else{
                error('注册失败!');
            }
        }
        return new View('user.register');
    }

    public function login(){
        if(IS_POST){
            $user=new UserModel();
            $data=$user->get(['email'=>$_POST['email']]);

            if($data){
                if($data[0]['password']==$_POST['password']){
                    $_SESSION['sns_user']=$data[0];
                    success('登陆成功','index');
                }else{
                    error('密码错误!');
                }
            }else{
                error('邮箱不存在!');
            }
        }
        return new View('user.login');
    }



    public function uploadPic(){
        if(IS_POST){
            $res=$this->upload();

            if($res){
                success('上传成功!','profile');
            }else{
                error('上传失败!');
            }
        }
    }



    public function upload(){
        p($_FILES);
        $file=$_FILES['pic'];
        if(!is_uploaded_file($file['tmp_name'])){
            return false;
        }
        //设置保存文件目录
        $path='./upload/'.date('Y-m-d',time()).'/';
        //判断是否是一个存在的目录,不存在则创建
        if(!is_dir($path)){
            mkdir($path,777,true);
        }
        //获取文件扩展名
        $extends=pathinfo($file['name']);
        $extends=$extends['extension'];
        //设置文件名
        $file_name=time().'_'.mt_rand(0,9999).'.'.$extends;
        //获取完整路径
        $up_path=$path.$file_name;
        //
        if(move_uploaded_file($file['tmp_name'], $up_path)){
            $user=new UserModel();
            $data['id']=$_SESSION['sns_user']['id'];
            $data['pic']=$up_path;
            $user->save($data);
            $_SESSION['sns_user']['pic']=$up_path;
            return true;
        }
        return false;
    }
}